<?

require_once('DataObject/DomainModel.php');
require_once('Statuses.php');
require_once('UsersRequests.php');
require_once('UsersFavourites.php');

class Users extends DomainModel {
	protected $id;	//primaryKey=yes, dataType=int, maxLength=, allowNulls=no
	protected $appsId;	//primaryKey=no, dataType=int, maxLength=, allowNulls=no
	protected $statusesId;	//primaryKey=no, dataType=int, maxLength=, allowNulls=no
	protected $username;	//primaryKey=no, dataType=varchar, maxLength=25, allowNulls=no
	protected $password;	//primaryKey=no, dataType=varchar, maxLength=512, allowNulls=no
	protected $firstName;	//primaryKey=no, dataType=varchar, maxLength=40, allowNulls=no
	protected $lastName;	//primaryKey=no, dataType=varchar, maxLength=40, allowNulls=no
	protected $email;	//primaryKey=no, dataType=varchar, maxLength=255, allowNulls=no
	protected $registrationDate;	//primaryKey=no, dataType=timestamp, maxLength=, allowNulls=no
	protected $lastUpdateDate;	//primaryKey=no, dataType=timestamp, maxLength=, allowNulls=no
	protected $isAdministrator;	//primaryKey=no, dataType=tinyint, maxLength=, allowNulls=no
	protected $isOperator;	//primaryKey=no, dataType=tinyint, maxLength=, allowNulls=no
	protected $systemRolesId;	//primaryKey=no, dataType=tinyint, maxLength=, allowNulls=no

	protected $saddrFirstName;	//primaryKey=no, dataType=varchar, maxLength=20, allowNulls=no
	protected $saddrLastName;	//primaryKey=no, dataType=varchar, maxLength=30, allowNulls=no
	protected $saddrEmail;	//primaryKey=no, dataType=varchar, maxLength=75, allowNulls=no
	protected $saddrStreet;	//primaryKey=no, dataType=varchar, maxLength=50, allowNulls=yes
	protected $saddrBuildingNo;	//primaryKey=no, dataType=varchar, maxLength=10, allowNulls=yes
	protected $saddrApartmentNo;	//primaryKey=no, dataType=varchar, maxLength=10, allowNulls=yes
	protected $saddrPostcode;	//primaryKey=no, dataType=varchar, maxLength=15, allowNulls=yes
	protected $saddrCity;	//primaryKey=no, dataType=varchar, maxLength=50, allowNulls=yes
	protected $saddrCountry;	//primaryKey=no, dataType=varchar, maxLength=50, allowNulls=yes
	protected $baddrCompanyName;	//primaryKey=no, dataType=varchar, maxLength=50, allowNulls=yes
	protected $baddrFirstName;	//primaryKey=no, dataType=varchar, maxLength=20, allowNulls=yes
	protected $baddrLastName;	//primaryKey=no, dataType=varchar, maxLength=30, allowNulls=yes
	protected $baddrEmail;	//primaryKey=no, dataType=varchar, maxLength=50, allowNulls=yes
	protected $baddrStreet;	//primaryKey=no, dataType=varchar, maxLength=50, allowNulls=yes
	protected $baddrBuildingNo;	//primaryKey=no, dataType=varchar, maxLength=10, allowNulls=yes
	protected $baddrApartmentNo;	//primaryKey=no, dataType=varchar, maxLength=10, allowNulls=yes
	protected $baddrPostcode;	//primaryKey=no, dataType=varchar, maxLength=15, allowNulls=yes
	protected $baddrCity;	//primaryKey=no, dataType=varchar, maxLength=50, allowNulls=yes
	protected $baddrCountry;	//primaryKey=no, dataType=varchar, maxLength=50, allowNulls=yes
	protected $baddrVatId;	//primaryKey=no, dataType=varchar, maxLength=100, allowNulls=yes
	protected $remarks;	//primaryKey=no, dataType=varchar, maxLength=500, allowNulls=yes
	protected $mainImageId;
	protected $mainImage;
	protected $status;
	protected $config;

	protected $offers;
	protected $requests;
	protected $favourites;
	
	public function getFavourites(){
		if (is_null($this->favourites)){
			$filter = "WHERE users_id = ".$this->id;
			$orderBy = "ORDER BY id DESC";
			$this->favourites = ModelMapper::instance('UsersFavourites')->findFiltered($filter, $orderBy);
		}
		
		return $this->favourites;
	}
	
	public function getOffers($filter = '', $orderBy = ''){
		if (is_null($this->offers)){
			$filter = "WHERE users_id = ".$this->id." ".$filter;
			$orderBy = "ORDER BY id DESC";
			$limit = 100;
			$offset = 0;
			
			$this->offers = ModelMapper::instance('Offers')->findFilteredPaged($filter, $orderBy, $limit, $offset);
		}
		
		return $this->offers;
	}
	
	public function getRequests($filter = '', $orderBy = ''){
		if (is_null($this->requests)){
			$filter = "WHERE users_id = ".$this->id." ".$filter;
			$orderBy = "ORDER BY id DESC";
			$limit = 100;
			$offset = 0;
			
			$this->requests = ModelMapper::instance('UsersRequests')->findFilteredPaged($filter, $orderBy, $limit, $offset);
		}
		
		return $this->requests;
	}
	
	public function getStatus(){
		if (is_null($this->status)){
			$this->status = ModelMapper::instance('Statuses')->find($this->statusesId);
		}
		
		return $this->status;
	}
	
	public function getConfig(){
		if (is_null($this->config)){
			$registry = Zend_Registry::getInstance();
			$config = $registry->get('config');
			$this->config = $config->uploads->users;
		}
		
		return $this->config;
	}
	
	public function getMainImage(){
		if (is_null($this->mainImage)){
			$this->mainImage = ModelMapper::instance('Files')->find($this->mainImageId);
		}
		
		return $this->mainImage;
	}
	
	public function getImageUrl(){
		if (!is_null($this->mainImageId)){
			return $this->getConfig()->origin_dir.'/'.$this->getMainImage()->getId().'.'.$this->getMainImage()->getExtension();
		}
		
	}
	
	function getThumb($width = '80', $height = '80', $method = 'zc'){
		if ($width == ''){
			$width = $this->getConfig()->thumbWidth;
		}
			
		if ($height == ''){
			$height = $this->getConfig()->thumbHeight;
		}
		
		if ($this->mainImageId != null){
			$image = '<img src="'.$this->getMainImage()->createThumb($this->getConfig()->origin_dir, $width, $height,$method).'" border="0" class="'.$this->getConfig()->cssId.'" />';
		} else {
			$tExt = 'png';
			$tClass = $this->getConfig()->cssId;
			$image = DataUtils::genThumb($width, $height, $this->getConfig()->no_file_image, $tClass, $tExt, $method);
		}
		return $image;
	}
	
}

class UsersMapper extends ModelMapper {
	function __construct(){
		parent::__construct();
		$this->tableName = 'users';
		$this->selectViewName = 'v_users';
		$this->selectFields = '
				id,
				apps_id,
				statuses_id,
				username,
				last_name,
				first_name,
				email,
				password,
				registration_date,
				last_update_date,
				is_administrator,
				is_operator,
				system_roles_id,
				saddr_first_name,
				saddr_last_name,
				saddr_email,
				saddr_street,
				saddr_building_no,
				saddr_apartment_no,
				saddr_postcode,
				saddr_city,
				saddr_country,
				baddr_company_name,
				baddr_first_name,
				baddr_last_name,
				baddr_email,
				baddr_street,
				baddr_building_no,
				baddr_apartment_no,
				baddr_postcode,
				baddr_city,
				baddr_country,
				baddr_vat_id,
				remarks,
				main_image_id,
				st_id,
				st_statuses_catalogues_id,
				st_status,
				st_description,
				sc_id,
				sc_catalogue
		';

		$this->findQuery = self::$DB->prepare("
			SELECT ".$this->selectFields."
			FROM ".$this->selectViewName."
			WHERE id = ?
		");
		$this->insertQuery = self::$DB->prepare("
			CALL p_add_users (@p_id,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?
		)");


		$this->updateQuery = self::$DB->prepare("
			CALL p_upd_users (
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?,
				?

		)");

		$this->deleteQuery = self::$DB->prepare("
			CALL p_del_users (?)
		");

		$this->cacheTime = null;
	}

	protected function doLoad($array){
		
		$acuire = str_replace('Mapper', '', get_class($this));
		$obj = new $acuire($array['id']);
		/*$obj->setId($array['id']);
		$obj->setAppsId($array['apps_id']);
		$obj->setStatusesId($array['statuses_id']);
		$obj->setUsername($array['username']);
		$obj->setPassword($array['password']);
		$obj->setFirstName($array['first_name']);
		$obj->setLastName($array['last_name']);
		$obj->setEmail($array['email']);
		$obj->setRegistrationDate($array['registration_date']);
		$obj->setLastUpdateDate($array['last_update_date']);
		$obj->setIsAdministrator($array['is_administrator']);
		$obj->setIsOperator($array['is_operator']);
		$obj->setSystemRolesId($array['system_roles_id']);
		$obj->setSaddrFirstName(isset($array['saddr_first_name'])?$array['saddr_first_name']:'');
		$obj->setSaddrLastName(isset($array['saddr_last_name'])?$array['saddr_last_name']:'');
		$obj->setSaddrEmail(isset($array['saddr_email'])?$array['saddr_email']:'');
		$obj->setSaddrStreet(isset($array['saddr_street'])?$array['saddr_street']:'');
		$obj->setSaddrBuildingNo(isset($array['saddr_building_no'])?$array['saddr_building_no']:'');
		$obj->setSaddrApartmentNo(isset($array['saddr_apartment_no'])?$array['saddr_apartment_no']:'');
		$obj->setSaddrPostcode(isset($array['saddr_postcode'])?$array['saddr_postcode']:'');
		$obj->setSaddrCity(isset($array['saddr_city'])?$array['saddr_city']:'');
		$obj->setSaddrCountry(isset($array['saddr_country'])?$array['saddr_country']:'');
		$obj->setBaddrCompanyName(isset($array['baddr_company_name'])?$array['baddr_company_name']:'');
		$obj->setBaddrFirstName(isset($array['baddr_first_name'])?$array['baddr_first_name']:'');
		$obj->setBaddrLastName(isset($array['baddr_last_name'])?$array['baddr_last_name']:'');
		$obj->setBaddrEmail(isset($array['baddr_email'])?$array['baddr_email']:'');
		$obj->setBaddrStreet(isset($array['baddr_street'])?$array['baddr_street']:'');
		$obj->setBaddrBuildingNo(isset($array['baddr_building_no'])?$array['baddr_building_no']:'');
		$obj->setBaddrApartmentNo(isset($array['baddr_apartment_no'])?$array['baddr_apartment_no']:'');
		$obj->setBaddrPostcode(isset($array['baddr_postcode'])?$array['baddr_postcode']:'');
		$obj->setBaddrCity(isset($array['baddr_city'])?$array['baddr_city']:'');
		$obj->setBaddrCountry(isset($array['baddr_country'])?$array['baddr_country']:'');
		$obj->setBaddrVatId(isset($array['baddr_vat_id'])?$array['baddr_vat_id']:'');
		$obj->setRemarks(isset($array['remarks'])?$array['remarks']:'');
		$obj->setMainImageId(isset($array['main_image_id'])?$array['main_image_id']:'');*/

		$arr = ArrayUtils::splitByPrefix($array, array('st_', 'sc_'));
		
		foreach ($array as $k=>$v){
			$kArray = explode('_', $k);
			$kName = '';
			foreach ($kArray as $val){
				$kName .= strtoupper(substr($val, 0, 1)).substr($val, 1, (strlen($val)-1));
			}
			
			$name = 'set'.$kName;
			//debug($name);
			$obj->$name($v);
		}
		
		
		if (!empty($arr['st_']))
			ModelMapper::instance('Statuses')->loadArray($arr['st_']);
		if (!empty($arr['sc_']))
			ModelMapper::instance('StatusesCatalogues')->loadArray($arr['sc_']);
			
		return $obj;
	}

	function insert(DomainModel $obj){

		$values = array(
			$obj->getAppsId(),
			$obj->getStatusesId(),
			$obj->getUsername(),
			$obj->getPassword(),
			$obj->getFirstName(),
			$obj->getLastName(),
			$obj->getEmail(),
			$obj->getRegistrationDate(),
			$obj->getLastUpdateDate(),
			$obj->getIsAdministrator(),
			$obj->getIsOperator(),
			$obj->getSystemRolesId(),
			$obj->getSaddrFirstName(),
			$obj->getSaddrLastName(),
			$obj->getSaddrEmail(),
			$obj->getSaddrStreet(),
			$obj->getSaddrBuildingNo(),
			$obj->getSaddrApartmentNo(),
			$obj->getSaddrPostcode(),
			$obj->getSaddrCity(),
			$obj->getSaddrCountry(),
			$obj->getBaddrCompanyName(),
			$obj->getBaddrFirstName(),
			$obj->getBaddrLastName(),
			$obj->getBaddrEmail(),
			$obj->getBaddrStreet(),
			$obj->getBaddrBuildingNo(),
			$obj->getBaddrApartmentNo(),
			$obj->getBaddrPostcode(),
			$obj->getBaddrCity(),
			$obj->getBaddrCountry(),
			$obj->getBaddrVatId(),
			$obj->getRemarks(),
			$obj->getMainImageId()
		);

		$this->doStatement($this->insertQuery, $values);
		$obj->setId(self::$DB->getOne("SELECT @p_id"));
	}

	function update(DomainModel $obj){
		$values = array(
			$obj->getId(),
			$obj->getAppsId(),
			$obj->getStatusesId(),
			$obj->getUsername(),
			$obj->getPassword(),
			$obj->getFirstName(),
			$obj->getLastName(),
			$obj->getEmail(),
			$obj->getRegistrationDate(),
			$obj->getLastUpdateDate(),
			$obj->getIsAdministrator(),
			$obj->getIsOperator(),
			$obj->getSystemRolesId(),
			$obj->getSaddrFirstName(),
			$obj->getSaddrLastName(),
			$obj->getSaddrEmail(),
			$obj->getSaddrStreet(),
			$obj->getSaddrBuildingNo(),
			$obj->getSaddrApartmentNo(),
			$obj->getSaddrPostcode(),
			$obj->getSaddrCity(),
			$obj->getSaddrCountry(),
			$obj->getBaddrCompanyName(),
			$obj->getBaddrFirstName(),
			$obj->getBaddrLastName(),
			$obj->getBaddrEmail(),
			$obj->getBaddrStreet(),
			$obj->getBaddrBuildingNo(),
			$obj->getBaddrApartmentNo(),
			$obj->getBaddrPostcode(),
			$obj->getBaddrCity(),
			$obj->getBaddrCountry(),
			$obj->getBaddrVatId(),
			$obj->getRemarks(),
			$obj->getMainImageId()
		);

		$this->doStatement($this->updateQuery, $values);
	}

	function delete(DomainModel $obj){
		$this->doStatement($this->deleteQuery, array($obj->getId()));
	}

	function newId(){

		$row = self::$DB->getRow('SHOW TABLE STATUS LIKE users');
		return $row['Auto_increment'];

	}
	
	function checkIsValidUsername($username){
		$query = "
			SELECT CASE WHEN NOT EXISTS (SELECT 1 FROM users WHERE username = '".$username."') THEN true ELSE false END
		";
		
		return (bool) self::$DB->getOne($query);
	}
}

class UsersCollection extends ModelCollection {
	function add(Users $model){
		$this->doAdd($model);
	}
}

class UsersCollectionExtended extends UsersCollection {
	private $stmt;
	private $valueArray;
	private $mapper;
	private $run = false;

	function __construct(ModelMapper $mapper, $stmtHandle, $valueArray){
		parent::__construct();
		$this->stmt = $stmtHandle;
		$this->valueArray = $valueArray;
		$this->mapper = $mapper;
	}

	function notifyAccess(){
		if (!$this->run){
			$result = $this->mapper->doStatement($this->stmt, $this->valueArray,$this->mapper->getCacheTime());
			$this->init_db($result, $this->mapper);
			$this->run = true;
		}
	}
}

?>